<?php
/**
 * 创建空模型文件，所有逻辑交给控制器
 */
namespace plugins\qbt_custom_model\service;
use think\Db;

class CreateModelService{
    public static function createModel($model_info){
        #nsh 20190107 修改
//        var_dump($model_info);exit;
        if($model_info['distinguish']==1){
            $path = str_replace("\\",DS,dirname(__DIR__)).DS.'data'.DS.'tpl'.DS.'category_models.tpl';
        }else if($model_info['distinguish']==2){
            $path = str_replace("\\",DS,dirname(__DIR__)).DS.'data'.DS.'tpl'.DS.'models.tpl';
        }

        $model_name_arr = explode("_",$model_info['model_tabname']);
        //首字母转大写
        $mname= '';
        if(count($model_name_arr)>1){
            foreach ($model_name_arr as $v){
                $mname.= ucfirst($v);
            }
        }else{
            $mname.= ucfirst($model_name_arr[0]);
        }
        $fileName = APP_PATH."admin/model/".$mname."Model.php";
        $content  = file_get_contents($path);
        #nsh 20190107 修改
        if($model_info['distinguish']==1){
            $model_field = Db::name('model_field')->where('model_id',$model_info['model_id'])->select()->toArray();
            $html='';
            foreach ($model_field as $item){
                if($item['field_is_index']==1&&$item['field_is_default']==0){
                    $html.= '<td>\$'.$item['field_name'].'</td>';
                }
            }
            $content = str_replace(array("#model_name#",'#CONTROLLERNAME#','#field_list#'),array($mname."Model",$model_info['model_controller'],$html),$content);
        }else if($model_info['distinguish']==2){
            $content = str_replace("#model_name#",$mname."Model",$content);
        }
        file_put_contents($fileName,$content);
    }
}